import { Injectable } from '@nestjs/common';
import { ObjectLiteral, Repository } from 'typeorm';
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';

@Injectable()
export class BaseService<T = ObjectLiteral> {
    protected model:Repository<T>;

    async querySql<E>(query: string) : Promise<E> {
        let res = await this.model.query(query)
        return res
    }

    async findOne(where? : {[key in keyof T]? : T[key]} | string, select? : Array<keyof T>, order? : {[key in keyof T] : 'ASC' | 'DESC'}) {
        let res = await this.model.findOne({
            select : select,
            where : where,
            order : order
        })

        return res ? res : null
    }

    async insert(data : QueryDeepPartialEntity<T> | (QueryDeepPartialEntity<T>[])) : Promise<number | null> {
        try {
            let res = await this.model.insert(data)
            let raw = res.raw
            if(raw && raw.affectedRows == 1) {
                return raw.insertId
            }
        } catch (error) {
            
        }
        
        return null
    }
}
